#include "codeview.h"
#include "windows.h"
#include "headers\BeaEngine.h"

CodeView::CodeView(QWidget *parent) : QTextEdit(parent)
{

}

void CodeView::loadCode(uint startAddress, uint size, uint virtualAddress)
{
    //init DISASM
    DISASM asmStruct;
    memset(&asmStruct, 0, sizeof(DISASM));

    asmStruct.EIP = startAddress;
    asmStruct.VirtualAddr = virtualAddress;

    bool isDecoding = true;
    while(isDecoding)
    {
        //specify how many bytes are safe to read, d.h. part of our region to decode
        asmStruct.SecurityBlock = startAddress + size - asmStruct.EIP;
        asmStruct.Options = Tabulation | MasmSyntax;
        int statusCode = Disasm(&asmStruct);
        if(statusCode == UNKNOWN_OPCODE)
        {
            //Unknown op code
            isDecoding = false;
        }
        else if(statusCode == OUT_OF_BLOCK)
        {
            //not in security block area
            isDecoding = false;
        }
        //statusCode is length of decoded bytes
        else
        {
            QString instructionString = QString("%1").arg((uint)asmStruct.EIP, 8, 16, QChar('0')) + " " + QString(asmStruct.CompleteInstr);
            this->append(instructionString);
            asmStruct.EIP = asmStruct.EIP + statusCode;
            if(asmStruct.EIP >= startAddress + size)
            {
                //Finished decoding the block
                isDecoding = false;
            }
        }
    }
}

